﻿using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Util.Interface;

namespace App
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterService();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

        public void Application_End() {

            return;
        }

        //private ContainerBuilder RegisterService()
        //{
        //    var builder = new ContainerBuilder();
        //    var baseType = typeof(IDependency);
        //    var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
        //    var AllServices = assemblys
        //        .SelectMany(s => s.GetTypes())
        //        .Where(p => baseType.IsAssignableFrom(p) && p != baseType);

        //    builder.RegisterControllers(assemblys.ToArray());
        //    builder.RegisterAssemblyTypes(assemblys.ToArray())
        //           .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
        //           .AsImplementedInterfaces().InstancePerLifetimeScope();
        //    return builder;
        //}

        //private void RegisterService() {

        //    ContainerBuilder builder = new ContainerBuilder();
        //  //  builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));
        //    Type baseType = typeof(IDependency);

        //    // 获取所有相关类库的程序集
        //    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        //    builder.RegisterControllers(assemblies);
        //    builder.RegisterAssemblyTypes(assemblies)
        //        .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
        //        .AsImplementedInterfaces().InstancePerLifetimeScope();//InstancePerLifetimeScope 保证对象生命周期基于请求
        //    IContainer container = builder.Build();
        //    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        //}

        public void RegisterService() {
            var builder = new ContainerBuilder();
            //获取IAutoInject的Type
            var baseType = typeof(IDependency);
            //获取所有程序集
            var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
            //自动注册接口
            builder.RegisterAssemblyTypes(assemblies).Where(b => b.GetInterfaces().
            Any(c => c == baseType && b != baseType)).AsImplementedInterfaces().InstancePerLifetimeScope();
            //自动注册控制器
            builder.RegisterControllers(assemblies);
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        }

    }
}
